<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/2/20 17:42
 * Desc: 后台用户
 */

namespace App\Models\Admin;


use App\Lib\Common;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Traits\HasRoles;

class AdminUser extends Authenticatable
{
    use HasFactory, Notifiable, HasRoles;

    protected $table = "admin_user";
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'real_name',
        'name',
        'email',
        'password',
        'salt',
        'mobile',
        'org_id',
        'org_code',
        'site_id',
        'avatar',
        'is_locked',
        'password_error_times',
        'password_last_fail_time',
        'login_time',
        'login_ip',
        'session_id',
        'pwd_init',
        'creator',
        'remember_token',
        'guard_name'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];


    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s'
    ];
    protected $primaryKey = "id"; //主键
    public $incrementing = true;  //主键是否自增
    public $timestamps = true;    //自动管理时间戳
    protected $dateFormat = "U";  //时间样式


    protected $scopeLimit = true;//数据查询范围,设置为true时,数据查询将自动增加site_id条件
    protected $declares = [
        "site_id" => ["site_id", "="],
        "is_locked" => ["is_locked", "="],
        "mobile" => ["mobile", "="],
    ];

    /**
     * 判断模型中是否存在某字段
     * @param string $column
     * @return bool
     */
    public function hasColumn($column) {
        return Schema::hasColumn($this->table, $column);
    }

    /**
     * 统一条件传入
     * @param array|null $condition
     * @return mixed
     */
    public function whereBuilder(array $condition = null) {
        $where = [];
        if ($condition) {
            foreach ($condition as $k => $v) {
                if (in_array($k, array_keys($this->declares)) && (!empty($v) || null != $v || "" != $v)) {
                    $where[] = array_merge($this->declares[$k], [$v]);
                }
            }
        }
        return $this->where($where);
    }


    //获取用户列表
    public function getAll($size, $where,$like=[]) {
        $whereOrg=empty($like)? []:$like;

        return self::whereBuilder($where)->where($whereOrg)->with("site","org")->where(function ($query){
            getCurrentSiteId() ==0?$query->where("is_system",1)->orWhere("site_id",getCurrentSiteId()):$query->where("site_id",getCurrentSiteId());
        })->orderBy("created_at","desc")->paginate($size)->toArray();
    }


    //显示用户详情
    public function userInfo($id) {
        $result = self::find($id);
        return $result;
    }

    //更新用户信息
    public function renew($params, $id) {
        $result = self::where("id", $id)->update($params);
        return $result;
    }


    //开启/禁用 用户
    public function onOrOff($params) {
        $result = self::where("id", $params['id'])->update(["is_locked" => $params["is_locked"]]);
        return $result;
    }

    //用户首次登录是否修改密码
    public function initOrNo($params) {
        $result = self::where("id", $params['id'])->update(["pwd_init" => $params["pwd_init"]]);
        return $result;
    }

    //用户自己修改密码
    public function changePwd($id, $password) {
        $salt = getCurrentUser()["salt"];
        //加密
        $password = (new Common())->passWord($salt, $password);
        //更新
        return self::where("id", $id)->update(["password" => $password, "pwd_init" => 0]);
    }

    //管理员/用户修改密码
    public function changeUserPwd($id, $params) {
        $user = self::find($id);
        $salt = $user->salt;
        //加密
        $password = (new Common())->passWord($salt, $params["password"]);
        //更新
        return self::where("id", $id)->update(["password" => $password, "pwd_init" => $params["pwd_init"]]);
    }

    //用户系统模式
    public function isSystem($id) {
        $result = self::where("id", $id)->pluck('is_system');
        return $result[0];
    }

    //验证登录密码
    public function getAuthPassword() {
        return ['password' => $this->attributes['password'], 'salt' => $this->attributes['salt']];
    }

    //获取用户拥有的角色
    public function getUserRoles(AdminUser $user){
        return self::with('role')->find($user->id);
    }

    //关联站点
    public function site() {
        return $this->belongsTo("App\Models\Admin\Site", "site_id", "id");
    }

    //关联组织机构
    public function org(){
        return $this->belongsTo("App\Models\Admin\Org", "org_id", "id");
    }

    //关联角色表
    public function role(){
        return $this->belongsToMany('App\Models\Admin\Role','model_has_roles','model_id','role_id')->withPivot('expire_at');
    }

    public function getRoles()
    {
        return $this->roles;
    }

    //关联用户分类
    public function category(){
        return $this->belongsToMany('App\Models\Category','permission_category','user_id','category_id')->withPivot('category_path','creator');
    }

}
